package com.yunxi.service.tms.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yunxi.bizToHub.pojo.CarRoadVO;
import com.yunxi.core.base.Constant;
import com.yunxi.core.web.ApiResult;
import com.yunxi.core.web.ResponseUtil;
import com.yunxi.eai.pojo.esb.EsbVO;
import com.yunxi.eai.pojo.tms.DespatchDataVO;
import com.yunxi.eai.pojo.tms.DespatchOrderVO;
import com.yunxi.eai.pojo.tms.IntoShopVO;
import com.yunxi.eai.pojo.tms.PositionTailVO;
import com.yunxi.eai.service.tms.TmsService;
import com.yunxi.model.eai.EaiLog;
import com.yunxi.parts.pojo.PrWaybillTransportCreateReqVO;
import com.yunxi.parts.service.EaiWaybillDubboService;
import com.yunxi.rocketmq.producer.EaiLogsProducer;
import com.yunxi.tmsToBiz.pojo.TmsIntoShopVO;
import com.yunxi.tmsToBiz.pojo.TmsNewTransportOrderVO;
import com.yunxi.tmsToBiz.pojo.TmsPositionTailVO;
import com.yunxi.tmsToBiz.service.TmsPartnerReceiveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2019/7/12.
 */
@Service
@Qualifier("tmsServiceImpl")
public class TmsServiceImpl implements TmsService {
    @Autowired
    private EaiLogsProducer eaiLogsProducer;
    protected static final Logger logger = LoggerFactory.getLogger(TmsServiceImpl.class);

    @Autowired
    TmsPartnerReceiveService tmsPartnerReceiveServiceImpl;
    @Autowired
    EaiWaybillDubboService eaiWaybillDubboServiceImpl;

    @Override
    public ApiResult distributeTms(EsbVO esbVO) {
        String serviceName = esbVO.getServiceName();
        ApiResult apiResult = null;
        if (serviceName.equals(Constant.TMS_PMS_DESPATCH_ORDER)) {
            apiResult = saveDespatchOrder(esbVO);
        }else if (serviceName.equals(Constant.TMS_PMS_INTO_SHOP)){
            apiResult = saveIntoShop(esbVO);
        }else if (serviceName.equals(Constant.TMS_PMS_POSITION_TAIL)){
            apiResult = savePositionTail(esbVO);
        }else if (serviceName.equals(Constant.TMS_PMS_CAR_ROAD)){
            apiResult = saveCarRoad(esbVO);
        }/*else if (serviceName.equals(Constant.TMS_PMS_LOGISTICS_INFORMATION_ROAD)){
            apiResult = saveLogisticsInformation(esbVO);
        }*/
        else {
            return ResponseUtil.fail(500, "没有对应的业务接口!");
        }
        return apiResult;
    }

   /* private ApiResult saveLogisticsInformation(EsbVO esbVO) {
        ApiResult apiResult = null;
        Map resultMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
        resultMap.put("zdate",sdf.format(new Date()));
        resultMap.put("ztime",sdf1.format(new Date()));
        String reqBody = esbVO.getReqBody();
        EaiLog eaiLog = new EaiLog();
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("TMS推送配件订单物流信息跟踪给UPS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
        try {
            //内部业务
            JSONObject jsonObject = JSON.parseObject(reqBody);
            List<PrWaybillTransportCreateReqVO> var1= JSON.parseObject(String.valueOf( jsonObject.get("jsonParame")), new TypeReference<ArrayList<PrWaybillTransportCreateReqVO>>() {});
            apiResult=eaiWaybillDubboServiceImpl.transport(var1);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode()==200){
                resultMap.put("zstat","S");
                resultMap.put("zmess","处理成功!");
            }else {
                resultMap.put("zstat","E");
                resultMap.put("zmess","处理失败!");
            }
            apiResult.setData(resultMap);
        } catch (Exception e) {
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(), e);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return apiResult;
    }*/

    private ApiResult saveCarRoad(EsbVO esbVO) {
        ApiResult apiResult = null;
        Map resultMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
        resultMap.put("zdate",sdf.format(new Date()));
        resultMap.put("ztime",sdf1.format(new Date()));
        String reqBody = esbVO.getReqBody();
        EaiLog eaiLog = new EaiLog();
        eaiLog.setEsbEaiContent(reqBody);
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("TMS推送小车车道给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(esbVO.getServiceName());
         ArrayList<CarRoadVO> carRoadList = JSON.parseObject(reqBody, new TypeReference<ArrayList<CarRoadVO>>() {});
        try {
            //内部业务
            TmsNewTransportOrderVO tmsNewTransportOrderVO=new TmsNewTransportOrderVO();
            for (int i = 0; i < carRoadList.size(); i++) {
                CarRoadVO carRoadVO =  carRoadList.get(i);
                tmsNewTransportOrderVO.setCarRoad(carRoadVO.getCarRoad());
                tmsNewTransportOrderVO.setLoadCode(carRoadVO.getLoadCode());
                tmsNewTransportOrderVO.setVin(carRoadVO.getVin());
                apiResult = tmsPartnerReceiveServiceImpl.updateCarRoad(tmsNewTransportOrderVO);
            }
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            if (apiResult.getCode()==200){
                resultMap.put("zstat","S");
                resultMap.put("zmess","处理成功!");
            }else {
                resultMap.put("zstat","E");
                resultMap.put("zmess","处理失败!");
            }
            apiResult.setData(resultMap);
        } catch (Exception e) {
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(), e);
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return apiResult;
    }

    /**
     * 地图跟踪信息
     * @param esbVO
     * @return
     */
    private ApiResult savePositionTail(EsbVO esbVO) {
        ApiResult apiResult = null;
        Map resultMap = new HashMap<>();
        String reqBody = esbVO.getReqBody();
        EaiLog eaiLog = new EaiLog();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("TMS地图跟踪信息推送给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.TMS_PMS_POSITION_TAIL);
        PositionTailVO positionTailVO= JSONObject.toJavaObject(JSON.parseObject(reqBody),PositionTailVO.class);
        try {
            //内部业务
            TmsPositionTailVO tmsPositionTailVO = JSONObject.parseObject(JSONObject.toJSONString(positionTailVO), TmsPositionTailVO.class);
            apiResult=tmsPartnerReceiveServiceImpl.updateVehicleLocationInfo(tmsPositionTailVO);
         /*   if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }*/
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            resultMap.put("zstat","S");
            resultMap.put("zmess","处理成功!");
            apiResult = ResponseUtil.ok(resultMap);
        } catch (Exception e) {
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(), e);
            /*resultMap.put("zstat","E");
            resultMap.put("zmess","处理失败!");*/
            apiResult = ResponseUtil.fail();
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }

    /**
     *到店信息
     * @param esbVO
     * @return
     */
    private ApiResult saveIntoShop(EsbVO esbVO) {
        ApiResult apiResult = null;
        Map resultMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
        resultMap.put("zdate",sdf.format(new Date()));
        resultMap.put("ztime",sdf1.format(new Date()));
        String reqBody = esbVO.getReqBody();
        EaiLog eaiLog = new EaiLog();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("TMS到店信息推送给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.TMS_PMS_INTO_SHOP);
      //  ArrayList<IntoShopVO> intoShopList = JSON.parseObject(String.valueOf( jsonObject.get("return")), new TypeReference<ArrayList<IntoShopVO>>() {});
        IntoShopVO intoShopVO= JSONObject.toJavaObject(JSON.parseObject(reqBody),IntoShopVO.class);

        try {
            //内部业务
            List<TmsIntoShopVO> list = new ArrayList<>();
         /*   for (int i = 0; i < intoShopList.size(); i++) {
                IntoShopVO intoShopVO =  intoShopList.get(i);
                TmsIntoShopVO tmsIntoShopVO=new TmsIntoShopVO();
                BeanUtils.copyProperties(intoShopVO,tmsIntoShopVO);
                list.add(tmsIntoShopVO);
            }*/
            TmsIntoShopVO tmsIntoShopVO=new TmsIntoShopVO();
            BeanUtils.copyProperties(intoShopVO,tmsIntoShopVO);
            list.add(tmsIntoShopVO);
            apiResult=tmsPartnerReceiveServiceImpl.savePartnerReceiveService(list);
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            resultMap.put("zstat","S");
            resultMap.put("zmess","处理成功!");
            apiResult = ResponseUtil.ok(resultMap);
        } catch (Exception e) {
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(), e);
        /*    resultMap.put("zstat","E");
            resultMap.put("zmess","处理失败!");*/
        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }

        return apiResult;
    }

    /**
     * 发运单信息
     * @param esbVO
     * @return
     */
    private ApiResult saveDespatchOrder(EsbVO esbVO) {
        ApiResult apiResult =null;
        Map resultMap = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf1 = new SimpleDateFormat("HH:mm:ss");
        resultMap.put("zdate",sdf.format(new Date()));
        resultMap.put("ztime",sdf1.format(new Date()));
        String reqBody = esbVO.getReqBody();
        apiResult = ResponseUtil.ok(resultMap);//设置默认返回VDC认证失败
        EaiLog eaiLog = new EaiLog();
        eaiLog.setEsbEaiContent(esbVO.getReqBody());
        eaiLog.setRequestSendTime(new Date());
        eaiLog.setFlowDesc("TMS发运单信息推送给PMS");
        eaiLog.setSourceSystem(Constant.PMS);
        eaiLog.setServiceName(Constant.TMS_PMS_DESPATCH_ORDER);
        DespatchOrderVO despatchOrderVO= JSONObject.toJavaObject(JSON.parseObject(reqBody),DespatchOrderVO.class);

        try {
            //内部业务
            //新增发运单
//            List<DespatchDataVO> vinLIst = despatchOrderVO.getVinLIst();
            TmsNewTransportOrderVO tmsNewTransportOrderVO = JSONObject.parseObject(JSONObject.toJSONString(despatchOrderVO), TmsNewTransportOrderVO.class);
//            List<String> vehicleList = new ArrayList<>();
//            if(despatchOrderVO.getVin() != null ){
//                    vehicleList.add(despatchOrderVO.getVin());
//            }
            //tmsNewTransportOrderVO.setVinLIst(vehicleList);
            apiResult=tmsPartnerReceiveServiceImpl.addTransportOrder(tmsNewTransportOrderVO);
           /* if (apiResult.getCode() == -1) {
                eaiLog.setDisposeStatus(2);
            }*/
            eaiLog.setResponseReceiveTime(new Date());
            eaiLog.setPmsResultContent(JSONObject.toJSONString(apiResult));
            resultMap.put("zstat","S");
            resultMap.put("zmess","处理成功!");
            apiResult = ResponseUtil.ok(resultMap);
        } catch (Exception e) {
            apiResult = ResponseUtil.fail();
            eaiLog.setDisposeStatus(2);
            logger.error(e.getMessage(), e);
         /*   resultMap.put("zstat","E");
            resultMap.put("zmess","处理失败!");*/

        }
        try {
            eaiLogsProducer.sendMessage(JSONObject.toJSONString(eaiLog));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return apiResult;
    }
}
